package com.sangeng.handler.exception;

import com.sangeng.constant.enums.AppHttpCodeEnum;
import com.sangeng.domain.core.ResponseResult;
import com.sangeng.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SystemException.class)
    public ResponseResult systemExceptionHandler(SystemException e){
        // 打印异常信息
        log.error("出现了异常！{}",e);
        // 从异常对象中获取提示信息封装返回给前端
        return ResponseResult.errorResult(e.getCode(),e.getMsg());
    }

    @ExceptionHandler(org.springframework.security.access.AccessDeniedException.class)
    public ResponseResult handleAccessDeniedException(org.springframework.security.access.AccessDeniedException e){
        // 设置响应状态码为 403 Forbidden
        log.error("权限不足！");
        // 返回 JSON 错误信息
        return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH.getCode(), AppHttpCodeEnum.NO_OPERATOR_AUTH.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult exceptionHandler(Exception e){
        // 打印异常信息
        log.error("出现了异常！{}",e);
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
    }
}
